"""
保存图片，求坐标中心点位置，判断点是否在多边形中



"""
import os
import yaml
import cv2
import requests
import time
import datetime
import numpy as np
from datetime import datetime
from shapely import geometry
# from shiju2.ezdl.ftp_utils import ftpconnect,uploadfile

sep = os.sep

# f = open('db_local.yaml')
# data = f.read()
# yaml_reader = yaml.load(data,Loader=yaml.CLoader)



# clas1 = None
# stream_img_path1 = None
# time = None
timestart = ""
timeend = ""
log_png = ""
#

def save_video(img,stream_img_path,timestart,timeend,clas):
    # with lock:
    # global timestart,timeend,log_png
    # timestart = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # timeend = after_one_minutes = (datetime.datetime.now() + datetime.timedelta(minutes=yaml_reader["video"]["min"])).strftime("%Y-%m-%d %H:%M:%S")
    # print("保存视频1")
    try:
        if timestart<timeend:
            print("保存视频2---------------------------------------------------------------")
            log_png = str(clas) + '_' + str(int(timestart)) + '.avi'
            local_video = stream_img_path + log_png

            out = cv2.VideoWriter(local_video, fource, yaml_reader["video"]["fps"], yaml_reader["video"]["shape"])

            out.write(img)

    except Exception as e:
        print(e)
    # finally:
    #     out.release()

def save_img(img,sx_ip,clas,img_path3,new_img_path,score,date):


    img_prements_path = img_path3 + sep
    local_img = img_prements_path + new_img_path
    # 进行保存图片
    cv2.imwrite(local_img, img, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])



    #调用java 的接口，进行数据提交
    # picture_path = f"http://192.168.31.67/uploads/{date}/{sx_ip}/{clas}/{new_img_path}"
    # try:
    #     url1 = "http://192.168.31.233:80/dev-api/alarmApi/insert"
    #
    #     # 发送请求
    #
    #     data1 = {
    #              "ip": sx_ip,
    #              "alarmType": clas,
    #              "accuracy": round(score,3),
    #              "date": date,
    #              "picture": picture_path
    #              }
    #     response = requests.post(url=url1, data=data1)
    # except Exception as e:
    #     print(e)

def image_processing(img,clas,img_path3,score_list,new_img_path,list_path,sx_ip,score,date):
    for img_item in list_path:
        old_score = float(img_item.split('_')[1])
        score_list.append(old_score)
    new_score = float(new_img_path.split('_')[1])
    if new_score >= np.mean(score_list):
        # 保存对应的照片
        save_img(img, sx_ip, clas, img_path3, new_img_path, score, date)
        # 删除score 最小的照片
        min_index = score_list.index(np.min(score_list))
        os.remove(img_path3 +sep+ list_path[min_index])
#img, sx_ip, clas, score, date
def img_pro(img,sx_ip,clas,score,date):
    score_list = []
    ROOT = os.getcwd()
    upload_path = r'data/uploads'

    # date = datetime.datetime.now().strftime("%Y-%m-%d")
    img_path1 = os.path.join(ROOT, upload_path + f'/{date}' + sep)
    if not os.path.exists(img_path1):
        os.mkdir(img_path1)
    img_path2 = img_path1 + str(sx_ip)
    if not os.path.exists(img_path2):
        os.mkdir(img_path2)
    img_path3 = img_path2+sep+str(clas)
    if not os.path.exists(img_path3):
        os.mkdir(img_path3)
    new_img_path  = str(clas) + '_' + str(round(score, 3)) + '_' + str(sx_ip) + "_" + str(datetime.now().strftime("%Y-%m-%d-%H-%M-%S")) + '.png'  # datetime.now().strftime("%Y-%m-%d%H:%M:%S")
    dirimg_len = len(os.listdir(img_path3))
    #img,clas,stream_img_path,sx_ip,score,date
    save_img(img,sx_ip,clas,img_path3,new_img_path,score,date) if int(dirimg_len) <= 200 else image_processing(img,clas,img_path3,score_list,new_img_path, os.listdir(img_path3),sx_ip,score,date)








def if_inPoly(polygon, Points):
    line = geometry.LineString(polygon)
    point = geometry.Point(Points)
    polygon = geometry.Polygon(line)
    return polygon.contains(point)


def get_coordinates(square):
    cnt = np.array(np.float32(square))  # 必须是array数组的形式
    rect = cv2.minAreaRect(cnt)  # 得到最小外接矩形的（中心(x,y), (宽,高), 旋转角度）

    return rect


if __name__ == '__main__':
    square = [(540, 577), (376, 655), (822, 792), (1404, 729),(1022,611)]
    print(if_inPoly(square,(623,670)))



